package com.zeroone.star.sample.controller;

import cn.hutool.core.date.DateTime;
import com.zeroone.star.project.components.easyexcel.EasyExcelComponent;
import com.zeroone.star.sample.test.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description 演示报表下载
 * @Author lyx
 * @since 2024/11/4 21:12
 */

@Controller
@RequestMapping("excel")
@Api(tags = "excel")
public class ExcelController {
    private List<User> dataList;

    @PostConstruct
    public void initData(){
        //构建测试数据
        dataList = new ArrayList<>(10);
        for (int i = 0; i < 10; i++) {
            User user = new User();
            user.setId(i);
            user.setName("测试用户" + i);
            user.setPhone("13600000" + i);
            dataList.add(user);
        }
    }

    @Resource
    EasyExcelComponent excel;

    @SneakyThrows
    @ApiOperation("下载报表")
    @GetMapping(value = "download",produces = "application/octet-stream")
    public ResponseEntity<byte[]> download(){
        //创建输出流
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        //将数据输出到输出流
        excel.export("测试下载",out, User.class,dataList);
        //响应给前端
        HttpHeaders httpHeaders = new HttpHeaders();
        String filename = "report-" + DateTime.now().toString("yyyyMMddHHmmss") + ".xlsx";
        httpHeaders.setContentDispositionFormData("attachment",filename);
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        ResponseEntity<byte[]> result = new ResponseEntity<>(out.toByteArray(), httpHeaders, HttpStatus.CREATED);
        out.close();
        return result;
    }
}
